/**
 *  *2010-6-14 上午01:26:03  add 
 */
package com.base.myproject.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.base.myproject.server.database.PoolMan;
import com.google.gwt.core.client.GWT;

/**
 * 写了几个文件上传，都不满意，那么我再写一个吧，避免影响之前的。
 * 
 * @author Administrator
 *2010-6-14
 * javazgw@gmail.com 
 */
public class BaseFileUploadServletFinal extends HttpServlet{
	private ServletConfig config;
	
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//response.setContentType("multipart/form-data;charset=UTF-8");
		//PrintWriter out = response.getWriter();
		//request.setCharacterEncoding("utf-8");
		
		 boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
//		 System.out.println(config.getServletContext().getRealPath("/"));
//		 System.out.println(config.getServletContext().getContextPath());
//		 System.out.println(config.getServletContext().getServerInfo());
		 GWT.log("is multipart? " + Boolean.toString(isMultipart), null);  
		 FileItemFactory factory = new DiskFileItemFactory();

		 ServletFileUpload upload = new ServletFileUpload(factory);  
		 Enumeration  enumeration=request.getParameterNames();
			
			while(enumeration.hasMoreElements())
			{
				String  eeee =""+ enumeration.nextElement();
				System.out.print("e="+eeee+"=");
				System.out.println(request.getParameter(""+eeee));
			}
			
			//传储存位置，如果不穿，就按照默认的方式储存图片
			String filestorepath = request
			.getParameter("filestorepath");
			String filepath ="";
			if(filestorepath!=null)
				 filepath = createfilepath(filestorepath);
			else
				 filepath = createfilepath();
		 try {
			FileItemIterator iter = upload.getItemIterator(request);
			while (iter.hasNext()) {  
				 FileItemStream item = iter.next();  
	                String name = item.getFieldName();  
	                
	                InputStream stream = item.openStream();  
	                
	                if (item.isFormField()) {  
	                    System.out.println("Form field " + name + " with value "  
	                            + Streams.asString(stream) + " detected.");  
	                } else {  
	                	 System.out.println("File field " + name  
	                             + " with file name " + item.getName()  
	                             + " detected.");  
	                	
	                	
	                	
							BufferedInputStream inputStream = new BufferedInputStream(
									stream);
							File f = createfile(item.getName(), filepath);
							BufferedOutputStream outputStream = new BufferedOutputStream(
									new FileOutputStream(f));

							Streams.copy(inputStream, outputStream, true);
							
							//war的路径
							String warpath = config.getServletContext()
							.getRealPath("/");

							String storefilepath = f.getPath().substring(
									warpath.length());
//							//表名
//							String table = request
//									.getParameter("tableinftablename");
//							//图片的名字
//							String imagepathcolumn = request
//									.getParameter("imagepath");
//							//字段名
//							String  columns = request
//							.getParameter("columns");
//							//字段值
//							String  values = request
//							.getParameter("values");

							if(request.getParameter("uploadcommand")!=null && request.getParameter("uploadcommand").equals("mankeflow"))
							{
								
							}
							//上传打印
							else if(  request.getParameter("uploadcommand") !=null &&request.getParameter("uploadcommand").equals("updateprint"))
							{
								String storesql =  request.getParameter("storesql");
								storesql = storesql.replaceAll("\\{filepath\\}", "'"+storefilepath+"'");
								PoolMan pm = new PoolMan();
								try {
									pm.Update(storesql);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								
								
							}
							
							
							else if(request.getParameter("uploadcommand") !=null &&request.getParameter("uploadcommand").equals("needsave"))
							{
								String table = request
									.getParameter("tableinftablename");

								String imagepathcolumn = request
								.getParameter("imagepath");
								
								String columns = request.getParameter("columns");
								String values = request.getParameter("values");
								storefilepath  =storefilepath.replaceAll("\\\\","/");
								System.out.println("storefilepath="+storefilepath);
								saveUpdateload(table, columns+imagepathcolumn, values+"'"+storefilepath+"'");
							}
								
							
//	                	 try {
//						//	saveUpdateload("ccodeimages","ccode","1001","idx","1001","imagepath",imagepath);
//	                		 saveUpdateload(table,key,keyvalue,idx,bcode,"imagepath",imagepath);
//						} catch (Exception e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
	                }
	                stream.close();  
			}
			 GWT.log("上传成功!",null);  
		//	 out.println("success");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }


	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	/**
	 * 设置路径，在war目录下创建 XXX的文件夹 ,uploadresourcepath 在web.xml里定义
	 * 
	 * @return
	 */
	public String createfilepath() {
		
		
		String filepath = config.getServletContext().getRealPath("/");
		String uploadresourcepath = config.getServletContext()
				.getInitParameter("uploadresourcepath");
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String a1 = sdf.format(new Date());
		filepath = filepath + uploadresourcepath + File.separatorChar + a1
				+ File.separatorChar;
	//filepath = filepath.replaceAll("\\", "/");
		return filepath;
	}
public String createfilepath(String uploadresourcepath) {
		
		
		
		String filepath = config.getServletContext().getRealPath("/");
		File fpath = new File(filepath+uploadresourcepath);
		if (!fpath.exists())
			fpath.mkdir();
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String a1 = sdf.format(new Date());
		filepath = filepath + uploadresourcepath + File.separatorChar + a1
				+ File.separatorChar;
	//	System.out.println("filepath="+filepath);
		//filepath = filepath.replaceAll("\\", "/");
		//System.out.println("filepath="+filepath);
		return filepath;
	}
	/**
	 * 根据文件名，指定路径，创建一个文件
	 * 
	 * @param file
	 * @param filepath
	 * @return
	 * @throws IOException
	 */

	public File createfile(String file, String filepath) throws IOException {
		System.out.println ("filepath="+filepath);
		File fpath = new File(filepath);
		if (!fpath.exists())
			fpath.mkdir();

		File f = new File(filepath + File.separatorChar + file);
		String fname = f.getName();

		java.lang.System.currentTimeMillis();
		while (f.exists()) {

			if (f.isFile()) {
				f = new File(filepath + File.separator
						+ java.lang.System.currentTimeMillis() + "" + fname);
			}

		}
		if (!f.exists()) {

			f.createNewFile();
		}
		GWT.log(f.getPath(), null);
		return f;

	}
	
	
	/**
	 * 
	 * @param table
	 *            表名
	 * @param key
	 *            主键名称
	 * @param keyvalue
	 *            主键值
	 * @param idxname
	 *            索引名称
	 * @param bcode
	 *            人员码
	 * @param imagespathcolumnname
	 *            图片储存数据库的路径字段名称
	 * @param filename
	 *            图片储存数据库的路径
	 * @throws Exception
	 */
	public void saveUpdateload(String table, String imagespathcolumnname,
			String filename) throws Exception {
		PoolMan pm = new PoolMan();

		String insertsql = "insert into " + table + "(" + imagespathcolumnname
				+ ") values(" + filename + ")";
		pm.Update(insertsql);

	}
	public static void main(String[] argv) throws IOException
	{
		 File f=new File("d:/temp/aa.tif");  
		 String fname =f.getName();
		 java.lang.System.currentTimeMillis();
		    while(f.exists())
	        {
	          
	             if(f.isFile())
	            {
	                f = new File(f.getParent()+File.separator+java.lang.System.currentTimeMillis()+""+fname);
	            }
	         
	        }
	       if(!f.exists())
	       {

	        f.createNewFile();
	       }
	}
	
	
}
